package com.nari.ncps.screen.service.impl.electric;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.electric.ElectricProdoperPowerGeneral;
import com.nari.ncps.screen.entity.ne.NeProdoperSalesPurchase;
import com.nari.ncps.screen.mapper.electric.ElectricProdoperPowerGeneralMapper;
import com.nari.ncps.screen.service.electric.ElectricProdoperPowerGeneralService;
import com.nari.ncps.screen.vo.electric.FdComplateTrend;
import com.nari.ncps.screen.vo.electric.FdPlanCompletionStatus;
import com.nari.ncps.screen.vo.electric.FdPowerPlantSupplyComplateStatus;
import com.nari.ncps.screen.vo.ne.NeSalesPurchaseVO;
import com.nari.ncps.screen.vo.wholeproduct.AnnualPowerGenerationVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 发电情况详情表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class ElectricProdoperPowerGeneralServiceImpl extends ServiceImpl<ElectricProdoperPowerGeneralMapper, ElectricProdoperPowerGeneral> implements ElectricProdoperPowerGeneralService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private ElectricProdoperPowerGeneralMapper electricProdoperPowerGeneralMapper;

    /**
     * 发电计划完成情况
     *
     * @param year  年份（可为空，默认当前年）
     * @param month 月份（可为空，默认当前月）
     * @return 发电计划完成情况
     */
    @Override
    public FdPlanCompletionStatus fdPlanCompletionStatus(Integer year, Integer month) {
        // 如果参数为空，使用当前年月
        if (year == null) {
            year = java.time.LocalDate.now().getYear();
        }
        if (month == null) {
            month = java.time.LocalDate.now().getMonthValue();
        }
//        if (orgCode == null) {
//            orgCode = "100360";
//        }
        // 创建返回对象
        FdPlanCompletionStatus status = new FdPlanCompletionStatus();
        status.setYear(year);
        status.setMonth(month);

        // 查询年数据（date_type = 0）
        LambdaQueryWrapper<ElectricProdoperPowerGeneral> yearQuery = new LambdaQueryWrapper<>();
        yearQuery.eq(ElectricProdoperPowerGeneral::getYear, year).eq(ElectricProdoperPowerGeneral::getOrgCode, "100360")
                .eq(ElectricProdoperPowerGeneral::getDateType, 0);  // 年数据
        yearQuery.orderByDesc(ElectricProdoperPowerGeneral::getUpdateTime);
        yearQuery.last("LIMIT 1");
//        List<ElectricProdoperPowerGeneral> yearDataList = this.list(yearQuery);
        ElectricProdoperPowerGeneral yearData = this.getOne(yearQuery);
        // 查询月数据（date_type = 1）
        LambdaQueryWrapper<ElectricProdoperPowerGeneral> monthQuery = new LambdaQueryWrapper<>();
        monthQuery.eq(ElectricProdoperPowerGeneral::getYear, year).eq(ElectricProdoperPowerGeneral::getMonth, month).eq(ElectricProdoperPowerGeneral::getOrgCode, "100360").eq(ElectricProdoperPowerGeneral::getDateType, 1);  // 月数据
        yearQuery.orderByDesc(ElectricProdoperPowerGeneral::getUpdateTime);
        yearQuery.last("LIMIT 1");
//        List<ElectricProdoperPowerGeneral> monthDataList = this.list(monthQuery);
        ElectricProdoperPowerGeneral monthData = this.getOne(monthQuery);

        if (yearData != null) {
            status.setAnnualPlanPower(yearData.getAnnualPlanPower());
            status.setAnnualActualPower(yearData.getAnnualActualPower());
            if(yearData.getAnnualActualPower() !=null) {
                status.setAnnualOverShortage(yearData.getAnnualActualPower().subtract(yearData.getAnnualPlanPower()));
            } else {
                status.setAnnualOverShortage(BigDecimal.ZERO);
            }

            if (yearData.getAnnualCompletionRate() != null && yearData.getAnnualCompletionRate() != BigDecimal.ZERO) {
                status.setAnnualCompletionRate(yearData.getAnnualCompletionRate());
            } else {
                if(yearData.getAnnualActualPower() !=null) {
                    status.setAnnualCompletionRate(yearData.getAnnualActualPower().divide(yearData.getAnnualPlanPower(), 2, RoundingMode.HALF_UP));
                } else {
                    status.setAnnualCompletionRate(BigDecimal.ZERO);
                }
            }
        }

        if (monthData != null) {
            status.setMonthlyPlanPower(monthData.getMonthlyPlanPower());
            status.setMonthlyActualPower(monthData.getMonthlyActualPower());
            if(monthData.getAnnualActualPower()!=null&&monthData.getAnnualActualPower()!=BigDecimal.ZERO&&monthData.getAnnualPlanPower()!=null){
                status.setMonthlyOverShortage(monthData.getAnnualActualPower().subtract(monthData.getAnnualPlanPower()));
            }
            if (monthData.getAnnualCompletionRate() != null && monthData.getAnnualCompletionRate() != BigDecimal.ZERO) {
                status.setMonthlyCompletionRate(monthData.getAnnualCompletionRate());
            } else {
                if (monthData.getMonthlyActualPower() != null) {
                    status.setMonthlyCompletionRate(monthData.getMonthlyActualPower().divide(monthData.getMonthlyPlanPower(), 2, RoundingMode.HALF_UP));
                } else {
                    status.setMonthlyCompletionRate(BigDecimal.ZERO);
                }
            }
        }

        // 处理年数据求和（如果有数据）
//        if (yearDataList != null && !yearDataList.isEmpty()) {
//            status.setAnnualPlanPower(yearDataList.stream()
//                    .map(ElectricProdoperPowerGeneral::getAnnualPlanPower)
//                    .filter(java.util.Objects::nonNull)
//                    .reduce(BigDecimal.ZERO, BigDecimal::add));
//
//            status.setAnnualActualPower(yearDataList.stream()
//                    .map(ElectricProdoperPowerGeneral::getAnnualActualPower)
//                    .filter(java.util.Objects::nonNull)
//                    .reduce(BigDecimal.ZERO, BigDecimal::add));
//
//            status.setAnnualCompletionRate(yearDataList.stream()
//                    .map(ElectricProdoperPowerGeneral::getAnnualCompletionRate)
//                    .filter(java.util.Objects::nonNull)
//                    .reduce(BigDecimal.ZERO, BigDecimal::add));
//
//            status.setAnnualOverShortage(yearDataList.stream()
//                    .map(ElectricProdoperPowerGeneral::getAnnualOverShortage)
//                    .filter(java.util.Objects::nonNull)
//                    .reduce(BigDecimal.ZERO, BigDecimal::add));
//        } else {
//            // 数据为空时，设置为0
//            status.setAnnualPlanPower(BigDecimal.ZERO);
//            status.setAnnualActualPower(BigDecimal.ZERO);
//            status.setAnnualCompletionRate(BigDecimal.ZERO);
//            status.setAnnualOverShortage(BigDecimal.ZERO);
//        }

        // 处理月数据求和（如果有数据）
//        if (monthDataList != null && !monthDataList.isEmpty()) {
//            status.setMonthlyPlanPower(monthDataList.stream()
//                    .map(ElectricProdoperPowerGeneral::getMonthlyPlanPower)
//                    .filter(java.util.Objects::nonNull)
//                    .reduce(BigDecimal.ZERO, BigDecimal::add));
//
//            status.setMonthlyActualPower(monthDataList.stream()
//                    .map(ElectricProdoperPowerGeneral::getMonthlyActualPower)
//                    .filter(java.util.Objects::nonNull)
//                    .reduce(BigDecimal.ZERO, BigDecimal::add));
//
//            status.setMonthlyCompletionRate(monthDataList.stream()
//                    .map(ElectricProdoperPowerGeneral::getMonthlyCompletionRate)
//                    .filter(java.util.Objects::nonNull)
//                    .reduce(BigDecimal.ZERO, BigDecimal::add));
//
//            status.setMonthlyOverShortage(monthDataList.stream()
//                    .map(ElectricProdoperPowerGeneral::getMonthlyOverShortage)
//                    .filter(java.util.Objects::nonNull)
//                    .reduce(BigDecimal.ZERO, BigDecimal::add));
//        } else {
//            // 数据为空时，设置为0
//            status.setMonthlyPlanPower(BigDecimal.ZERO);
//            status.setMonthlyActualPower(BigDecimal.ZERO);
//            status.setMonthlyCompletionRate(BigDecimal.ZERO);
//            status.setMonthlyOverShortage(BigDecimal.ZERO);
//        }

        return status;
    }

    /**
     * 发电量完成趋势
     *
     * @param year 年份（可为空，默认当前年）
     * @return 包含今年和去年各月份发电量的趋势列表
     */
    @Override
    public List<FdComplateTrend> fdComplateTrend(Integer year) {

        List<FdComplateTrend> voList = new ArrayList<>();

        // 获取当前时间
        LocalDate now = LocalDate.now();

        // 计算过去12个月的年份和月份（从当前月往前推11个月，共12个月）
        List<String> statisticTimes = new ArrayList<>();
        for (int i = 11; i >= 0; i--) {
            LocalDate date = now.minusMonths(i);
            String statisticTime = String.format("%d%02d", date.getYear(), date.getMonthValue());
            statisticTimes.add(statisticTime);
        }

        // 构建查询条件
        LambdaQueryWrapper<ElectricProdoperPowerGeneral> lqw = new LambdaQueryWrapper<>();
        lqw.in(ElectricProdoperPowerGeneral::getStatisticTime, statisticTimes)
                .eq(ElectricProdoperPowerGeneral::getOrgCode, "100360")
                .eq(ElectricProdoperPowerGeneral::getDateType, 1)
                .orderByAsc(ElectricProdoperPowerGeneral::getStatisticTime);

        // 执行查询
        List<ElectricProdoperPowerGeneral> entityList = electricProdoperPowerGeneralMapper.selectList(lqw);

        // 按statistic_time分组
        Map<String, ElectricProdoperPowerGeneral> entityMap = entityList.stream()
                .collect(Collectors.toMap(ElectricProdoperPowerGeneral::getStatisticTime,
                        entity -> entity, (existing, replacement) -> existing));

        // 创建VO对象
        FdComplateTrend vo = new FdComplateTrend();

        // 设置年份为当前年份
        vo.setYear(now.getYear());

        // 按月份设置数据（从mth_1到mth_12）
        for (int i = 0; i < 12; i++) {
            LocalDate date = now.minusMonths(11 - i); // 从最早月份开始到最新月份
            String statisticTime = String.format("%d%02d", date.getYear(), date.getMonthValue());

            ElectricProdoperPowerGeneral entity = entityMap.get(statisticTime);
            BigDecimal monthlyActualPower = entity != null ? entity.getMonthlyActualPower() : null;

            // 根据月份索引设置对应的字段
            switch (i) {
                case 0: vo.setMth_1(monthlyActualPower); break;
                case 1: vo.setMth_2(monthlyActualPower); break;
                case 2: vo.setMth_3(monthlyActualPower); break;
                case 3: vo.setMth_4(monthlyActualPower); break;
                case 4: vo.setMth_5(monthlyActualPower); break;
                case 5: vo.setMth_6(monthlyActualPower); break;
                case 6: vo.setMth_7(monthlyActualPower); break;
                case 7: vo.setMth_8(monthlyActualPower); break;
                case 8: vo.setMth_9(monthlyActualPower); break;
                case 9: vo.setMth_10(monthlyActualPower); break;
                case 10: vo.setMth_11(monthlyActualPower); break;
                case 11: vo.setMth_12(monthlyActualPower); break;
            }
        }
        voList.add(vo);
        return voList;
    }

    /**
     * 从数据库查询并设置月度数据（使用 MyBatis-Plus，按 date_type = 1 查询月数据）
     *
     * @param trend FdComplateTrend对象
     * @param year  年份
     */
    private void setMonthlyDataFromDb(FdComplateTrend trend, Integer year) {
        // 初始化所有月份为0，避免null值
        trend.setMth_1(BigDecimal.ZERO);
        trend.setMth_2(BigDecimal.ZERO);
        trend.setMth_3(BigDecimal.ZERO);
        trend.setMth_4(BigDecimal.ZERO);
        trend.setMth_5(BigDecimal.ZERO);
        trend.setMth_6(BigDecimal.ZERO);
        trend.setMth_7(BigDecimal.ZERO);
        trend.setMth_8(BigDecimal.ZERO);
        trend.setMth_9(BigDecimal.ZERO);
        trend.setMth_10(BigDecimal.ZERO);
        trend.setMth_11(BigDecimal.ZERO);
        trend.setMth_12(BigDecimal.ZERO);

        // 使用 MyBatis-Plus 查询月数据（date_type = 1）
        LambdaQueryWrapper<ElectricProdoperPowerGeneral> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ElectricProdoperPowerGeneral::getYear, year).eq(ElectricProdoperPowerGeneral::getDateType, 1);  // date_type = 1 表示月数据

        List<ElectricProdoperPowerGeneral> monthDataList = this.list(queryWrapper);

        // 如果数据为空，直接返回（所有月份都是0）
        if (monthDataList == null || monthDataList.isEmpty()) {
            return;
        }

        // 按月份分组，对相同月份的数据求和
        Map<Integer, BigDecimal> monthSumMap = new java.util.HashMap<>();
        for (ElectricProdoperPowerGeneral data : monthDataList) {
            Integer month = data.getMonth();
            BigDecimal actualPower = data.getMonthlyActualPower();

            if (month != null && actualPower != null) {
                monthSumMap.merge(month, actualPower, BigDecimal::add);
            }
        }

        // 将汇总后的数据设置到对应月份
        for (Map.Entry<Integer, BigDecimal> entry : monthSumMap.entrySet()) {
            Integer month = entry.getKey();
            BigDecimal totalActualPower = entry.getValue();

            switch (month) {
                case 1:
                    trend.setMth_1(totalActualPower);
                    break;
                case 2:
                    trend.setMth_2(totalActualPower);
                    break;
                case 3:
                    trend.setMth_3(totalActualPower);
                    break;
                case 4:
                    trend.setMth_4(totalActualPower);
                    break;
                case 5:
                    trend.setMth_5(totalActualPower);
                    break;
                case 6:
                    trend.setMth_6(totalActualPower);
                    break;
                case 7:
                    trend.setMth_7(totalActualPower);
                    break;
                case 8:
                    trend.setMth_8(totalActualPower);
                    break;
                case 9:
                    trend.setMth_9(totalActualPower);
                    break;
                case 10:
                    trend.setMth_10(totalActualPower);
                    break;
                case 11:
                    trend.setMth_11(totalActualPower);
                    break;
                case 12:
                    trend.setMth_12(totalActualPower);
                    break;
            }
        }
    }

    /**
     * 各个电厂供电完成情况
     *
     * @param year 年份
     * @return 电厂供电完成情况列表
     */
    @Override
    public List<FdPowerPlantSupplyComplateStatus> fdPowerPlantSupplyComplateStatus(Integer year) {
        List<String> orgCodeList = Arrays.asList("10000173","10000167","10000168","10000169",
                "10000166","10000164","10000165","10000163","10000170","10000162","10000172",
                "10000171","10001120","10001200");
        LambdaQueryWrapper<ElectricProdoperPowerGeneral> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(ElectricProdoperPowerGeneral::getOrgCode, orgCodeList)
                .eq(ElectricProdoperPowerGeneral::getDateType, 0)
                .eq(ElectricProdoperPowerGeneral::getYear, year);
        List<ElectricProdoperPowerGeneral> dataList = this.list(wrapper);
        List<FdPowerPlantSupplyComplateStatus> result = new ArrayList<>();

        for(ElectricProdoperPowerGeneral data : dataList){
            FdPowerPlantSupplyComplateStatus vo = new FdPowerPlantSupplyComplateStatus();
            vo.setYear( year);
            vo.setPowerPlantCode(data.getOrgCode());
            vo.setPowerPlantName(data.getOrgName());
            vo.setAnnualPlanPower(data.getAnnualPlanPower());
            vo.setAnnualActualPower(data.getAnnualActualPower());
            result.add(vo);
        }
        return result;
    }

    /**
     * 获取年度发电完成情况（最近5年）
     *
     * @return 年度发电完成情况列表
     */
    @Override
    public List<AnnualPowerGenerationVO> getAnnualPowerGeneration() {
        // 从数据库查询年度汇总数据
        List<ElectricProdoperPowerGeneral> annualStatsList = baseMapper.getAnnualPowerGenerationStats();

        // 转换为VO对象
        List<AnnualPowerGenerationVO> resultList = new ArrayList<>();
        for (ElectricProdoperPowerGeneral entity : annualStatsList) {
            AnnualPowerGenerationVO vo = new AnnualPowerGenerationVO();
            vo.setYear(entity.getYear());
            vo.setAnnualPlanPower(entity.getAnnualPlanPower());
            vo.setAnnualActualPower(entity.getAnnualActualPower());

            // 计算完成率：实际发电量 / 计划发电量 * 100
            if (entity.getAnnualPlanPower() != null && entity.getAnnualPlanPower().compareTo(BigDecimal.ZERO) != 0) {
                BigDecimal completionRate = entity.getAnnualActualPower().divide(entity.getAnnualPlanPower(), 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP);
                vo.setAnnualCompletionRate(completionRate);
            } else {
                vo.setAnnualCompletionRate(BigDecimal.ZERO);
            }
            resultList.add(vo);
        }
        resultList.sort(Comparator.comparingInt(AnnualPowerGenerationVO::getYear));
        return resultList;
    }
}